package solutions;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.schema.Column;
import objects.Table;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class InsertSolution {
    public static void Insert(String path, String database, String tablename, List<Column> columns, ExpressionList expressions) {
        File filedat = new File(path + "/" + database + "/" + tablename + ".dat");
        File filetsc = new File(path + "/" + database + "/" + tablename + ".tsc");
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filetsc))) {
            Table table = (Table) ois.readObject();

            if (!filedat.exists()) {
                System.out.println("ERROR:table doesn't exists");
            } else {
                String temp = "";
                int k = 0;
                for (int j = 0; j < table.getColumnList().size(); j++) {
                    if (columns.get(j).equals(expressions.get(k))) {
                        temp += expressions.getExpressions().get(j);
                        temp += ',';
                        k++;
                    }else{
                        temp += ',';
                    }
                }
                temp += "|";
                byte[] tempByte = temp.getBytes(StandardCharsets.UTF_8);
                FileOutputStream fos = new FileOutputStream(path + "/" + database + "/" + tablename + ".dat");
                fos.write(tempByte);
                fos.close();
                System.out.println("Query OK");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
